from datetime import datetime

from flask import Blueprint, make_response
from webargs import fields
from webargs.flaskparser import use_args

from app import ts_client
from app.clients.prometheus_client import prometheus_connect
from app.models.user_info import UserInfo

prometheus = Blueprint('prometheus', __name__)

labels_field = {
    'label': fields.Str(required=True),
    'value': fields.Str(required=True)
}

query_range_args = {
    'labels': fields.List(fields.Nested(labels_field), required=True)
}


@prometheus.post('/query_range')
@use_args({'x-wx-openid': fields.Str(required=True)}, location='headers')
@use_args(query_range_args, location='json')
def query_range(headers_json: dict, request_json: dict):
    open_id = headers_json.get('x-wx-openid')
    user_info: UserInfo = ts_client.query(UserInfo.generate_rowkey(open_id), UserInfo)
    if user_info is None:
        return make_response({
            'code': 100001,
            'msg': 'not found user'
        })
    else:
        labels: list = request_json.get('labels')
        labels.append({
            "label": "phone_number",
            "value": user_info.phone_number
        })
        query = "{" + ", ".join([f'{label["label"]}="{label["value"]}"' for label in labels]) + "}"
        prom_response = prometheus_connect.custom_query_range(
            query=f"uplink_bandwidth_usage{query}",
            start_time=datetime.fromtimestamp(int(datetime.now().timestamp()) - (3600 * 6)),
            end_time=datetime.now(),
            step='60s'
        )
        return make_response(prom_response)
